<template>
  <div class="app-container">
    <!--搜索框-->
    <el-form v-model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item lable="问卷名称">
        <el-input type="text" v-model="queryParams.surveyName" placeholder="请输入问卷名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getSurveyList">检索</el-button>
      </el-form-item>
    </el-form>

    <!--数据展示-->
    <el-table
      :data="surveyData"
      style="width: 100%">
      <el-table-column prop="surveyName" align="center" label="问卷名称"/>
      <el-table-column prop="formNum" align="center" label="提交问卷数"/>
      <el-table-column prop="formUrl" align="center" label="问卷地址"/>
      <el-table-column prop="isRelease" align="center" label="是否发布">
        <template slot-scope="scope">
          {{ scope.row.isRelease == 0 ? '否' : '是' }}
        </template>
      </el-table-column>
      <el-table-column prop="isSound" align="center" label="录音功能">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isSound"
                     :active-value="1"
                     :inactive-value="0"@change="handleSound(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="confirmSurvey(scope.row)"> 发布</el-button>
          <el-button type="text" size="mini" @click="handleEidt(scope.row)"> 编辑</el-button>
          <el-button type="text" size="mini" @click="getSurveyInfo(scope.row)">预览</el-button>
          <el-button type="text" size="mini" @click="handleExport(scope.row)"> 导出</el-button>
          <el-button type="text" size="mini" @click="handleFormDataS(scope.row)"> 查看提交数据</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getSurveyList"
    />
    <!--预览窗口 -->
    <el-dialog title="预览"
               :visible.sync="dialogVisible"
               :before-close="handleClose">
      <div class="app-container">
        <div v-if="isSound" v-show="isSound!=0">
          <div style="display: flex;justify-content: center;padding-bottom: 5px">
            <audio v-show="recorderEnd" controls ref="audio" muted="muted" src="" id="audio"></audio>
          </div>
          <div  style="display: flex;justify-content: center;padding-bottom: 5px">
            <el-button size="mini" type="primary"  @click="startRecoder()">开始录音</el-button>
            <el-button size="mini" type="success"  @click="stopRecoder()">结束录音</el-button>
            <el-button size="mini" type="warning"  @click="cancelRecoder()">取消录音</el-button>
          </div>
        </div>
        <form-create v-model="fApi" :rule="rule" :option="option" :value.sync="value"></form-create>
      </div>
    </el-dialog>
    <!-- 查看提交数据 -->
    <el-dialog :title="title" width="80%" :visible.sync="formDialogVisible">
      <el-table :data="formTable">
        <el-table-column fixed label="行" type="index"/>
        <el-table-column v-for="name in tableTitleJson" :key="name" align="center">
          <template slot="header" slot-scope="scope">
            <span>{{ name }}</span>
          </template>
          <template slot-scope="scope">
            <div v-html="validURL(JSON.parse(scope.row.form)[name])"></div>
            <!--            <el-button type="primary" icon="el-icon-edit" @click="tets">111</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="formTotal>0"
        :total="formTotal"
        :page.sync="formQueryParams.pageNum"
        :limit.sync="formQueryParams.pageSize"
        @pagination="getFormTableList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {list, surveryInfo, confirmRelease,confirmSound} from "@/api/survery/form";
import {saveSurvery, list as formDataLit} from "@/api/survery/data";
import {Notification, MessageBox, Message, Loading} from 'element-ui';
import Recorder from "js-audio-recorder";
import axios from "axios";
import uniqueId from '@form-create/utils/lib/unique';
var recorder;
let LoadingS;
import '../../../utils/crypto1/crypto/crypto'
import '../../../utils/crypto1/hmac/hmac'
import '../../../utils/crypto1/sha1/sha1'
import { Base64 } from 'js-base64'

/**
 * 生成policy和签名
 * 默认1小时后失效
 * @param {*} accessKeySecret oss accessKeySecret
 * @param {*} expiration 过期时间 单位秒
 * @returns
 */
function genSignature (fileName) {
  console.log(fileName)
  const accessKeySecret = 'ZNVPLxgMYGa7CZsghYOVnyOyyJOGFv';
  const expiration = (new Date(Date.now() +  1200 * 1000)).toISOString()
  const policy = {
    expiration: expiration, // 失效时间
    conditions: [
      ['content-length-range', 0, 469824028] // 设置上传文件的大小限制 1G
    ]
  }
  const policyBase64 = Base64.encode(JSON.stringify(policy))

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accessKeySecret, { asBytes: true });
  const signature = Crypto.util.bytesToBase64(bytes);

  return {
    OSSAccessKeyId:'LTAI5tEewCaBy7zsdcL6GmVT',
    policy:policyBase64,
    key:fileName,
    success_action_status:'200',
    signature
  }
}

export default {
  data() {
    return {
      queryParams: {
        id: undefined,
        surveyName: undefined,
        rule: undefined,
        option: undefined,
        isSound: undefined,
        isRelease: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      //表单提交数据
      title: '',
      tableTitleJson: [],
      formTable: [],
      formTotal: 0,
      formQueryParams: {
        id: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      formDialogVisible: false,
      isReleaseData: [{label: "是", value: "1"}, {label: "否", value: "0"}],
      surveyData: [],
      dialogVisible: false,
      //预览参数
      //实例对象
      fApi: {},
      //表单数据
      value: {},
      //表单生成规则
      rule: [],
      //组件参数配置
      option: {},
      //提交参数
      data: {},
      // coode
      cood: 0,
      isSound:undefined,
      recoderSecond: 0,
      recorderAudio: null,
      talkBtnText: "按住 说话",
      recorderEnd: true,

    }
  },

  created() {
    this.getSurveyList();
  },
  methods: {
    validURL(url) {
      var data;
      var datas;
      const reg = /^(http|https):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
      if (url.indexOf(',') >= 0) {
        datas = url.split(',')
        for (let i = 0; i <= datas.length; i++) {
          if (reg.test(datas[i]) ) {

            if(this.isAssetlypeAn(datas[i])){
              var html = '';
              for (let i = 0; i < datas.length; i++) {
                html += `<button style="border:none" onclick="window.open('${datas[i]}')">
                     <img src=${datas[i]} @click=${datas[i]} alt="" style="width: 45px;height: 45px;padding-right: 2px">
                     </button>`
              }
              return html;
            }else{
              var html = '';
              for (let i = 0; i < datas.length; i++) {
                html += `<button style="border:none" onclick="window.open('${datas[i]}')">查看 </button>`
              }
              return html;
            }
          } else {
            return url;
          }
        }
      } else {
        if (reg.test(url)) {
          if(this.isAssetlypeAn(url))
            return `<button style="border:none" onclick="window.open('${url}')">
                  <img src=${url} @click=${url} alt="" style="width: 45px;height: 45px;padding-right: 2px">
                  </button>`
          else  return `<a style="border:none" onclick="window.open('${url}')">查看</a>`
        } else {
          return url;
        }

      }
    },
    isAssetlypeAn(ext) {
      if(ext.toLowerCase().indexOf('.png')>-1||ext.toLowerCase().indexOf('.jpg')>-1||ext.toLowerCase().indexOf('.jpeg')>-1)
        return true;
      else return false;
    },

    getSurveyList() {
      list(this.queryParams).then(res => {
        this.total = res.total;
        this.surveyData = res.rows;
      })
    },
    getSurveyInfo(e) {
      surveryInfo(e.id).then(res => {
        this.data.surverId = e.id;
        this.isSound = res.data.isSound;
        //处理规则中类型为上传的控件信息
        var rule = res.data.rtformRules;
        console.log(rule);
        for (var i = 0; i < res.data.rtformRules.length; i++) {
          if (rule[i].type == "upload") {
            //const filename2 = new Date().getTime()+"_"+i;
            var filename2 = "";
            var title = rule[i].title

            // rule[i].props.data = genSignature(filename2);
            rule[i].props.onSuccess = function (res, file) {
              file.url = "https://img.cscxsk.cn/"+ filename2;
              Message({message: title + "上传成功!", type: 'success'})
              LoadingS.close();
            }
            rule[i].emit=['before-upload'];
            rule[i].props.beforeUpload = function (file) {
              filename2 =file.name;
              LoadingS = Loading.service({
                text: "正在上传，请稍候",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
              })
            };
            rule[i].props.onError = function (file) {
              Message({message: title + "上传失败!", type: 'error'})
              LoadingS.close();
            }
          }
        }

        this.rule = rule;
        // this.fApi = formCreate(rule,res.data.rtformOption)
        // this.fApi.on('2222-on-change',() => {
        //   //TODO
        // })

        //处理form表单 默认提交按钮
        this.option = res.data.rtformOption;

        this.option.onSubmit = function (formData) {
          if(recorder){
            var blob = recorder.getWAVBlob();
            var formDataq = new FormData()
            // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
            const newbolb = new Blob([blob], { type: 'audio/wav' })
            //获取当时时间戳作为文件名
            const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
            formDataq.append('file', fileOfBlob)
            axios.post(process.env.VUE_APP_BASE_API+"/common/AliUpload",formDataq).then(res =>{
              console.log(res.data)
              formData['录音地址'] = res.data.url;
              for (var key in formData) {
                if (typeof formData[key] == "object") {
                  formData[key] = formData[key].join(',')
                }
              }
              const data = {"surverId": e.id, "form": JSON.stringify(formData)};
              saveSurvery(data).then(res => {
                alert("提交成功！")
              })
            })
          }else{
            for (var key in formData) {
              if (typeof formData[key] == "object") {
                formData[key] = formData[key].join(',')
              }
            }
            const data = {"surverId": e.id, "form": JSON.stringify(formData)};
            saveSurvery(data).then(res => {
              alert("提交成功！")
              location.reload();
            })
          }
        };
        this.dialogVisible = true;
      })
    },
    startRecoder() {
      recorder = new Recorder();
      this.recorderAudio = document.querySelector('#audio');
      recorder.start();
    },
    stopRecoder() {
      if (!recorder) {
        return;
      }
      var blob = recorder.getWAVBlob();
      document.querySelector('#audio').src = URL.createObjectURL(blob);
      document.querySelector('#audio').controls = true;
      // var formDataq = new FormData()
      // // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
      // const newbolb = new Blob([blob], { type: 'audio/wav' })
      // //获取当时时间戳作为文件名
      // const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
      // formDataq.append('file', fileOfBlob)
      // axios.post(process.env.VUE_APP_BASE_API+"/common/AliUpload",formDataq)

    },
    cancelRecoder() {
      this.recoderSecond=0;
      if(!recorder){
        return;
      }
      recorder.destroy();
      document.querySelector('#audio').src = '';
      recorder=null;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    /** 导出按钮操作 */
    handleExport(e) {
      this.download('survery/exportss', {id: e.id}, `${new Date().getTime()}.xlsx`)
    },
    /**编辑**/
    handleEidt(e) {
      this.$router.push({name: 'Survey', params: {id: e.id}})
    },
    /**查看提交数据**/
    getFormTableList() {
      formDataLit(this.formQueryParams).then(res => {
        this.formTable = res.rows;
        this.formTotal = res.total;
        this.tableTitleJson = Object.keys(JSON.parse(res.rows[0].form));
      })
    },
    handleFormDataS(e) {
      this.title = e.surveyName;
      this.formQueryParams.id = e.id;
      this.formDialogVisible = true;
      this.getFormTableList();
    },

    /**
     * 开启录音功能
     */
    handleSound(e){
      confirmSound(e);
    },
    /**发布*/
    confirmSurvey(e) {
      var url = window.location.origin;
      var data = Object.assign({}, e)
      data.formUrl = url;
      this.$modal.confirm('是否确认发布名称为"' + e.surveyName + '"的问卷？').then(() => {
        confirmRelease(data).then(res => {
          this.getSurveyList();
        })
      }).catch(() => {
      });
    }
  }
}
</script>

<style scoped>

</style>
